package com.clkj.mobileinspector.ui.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.model.ObserverOnNext;
import com.clkj.mobileinspector.model.OkHttpUtils;
import com.clkj.mobileinspector.model.bean.PolicedeptBean;
import com.clkj.mobileinspector.model.bean.ProblemtypeBean;
import com.clkj.mobileinspector.model.bean.QueryBean;
import com.clkj.mobileinspector.model.bean.QuerySuccessBean;
import com.clkj.mobileinspector.model.bean.ResourceApi;
import com.clkj.mobileinspector.ui.activity.InspectorRecordActivity;
import com.clkj.mobileinspector.ui.activity.MainActivity;
import com.clkj.mobileinspector.ui.activity.SafeguardRightsActivity;
import com.clkj.mobileinspector.ui.activity.StatisticsActivity;
import com.clkj.mobileinspector.ui.adapter.ListFragmentAdapter;
import com.clkj.mobileinspector.utils.JsonUtils;
import com.clkj.mobileinspector.utils.LogUtils;
import com.clkj.mobileinspector.utils.ResourceApiUtils;
import com.google.gson.reflect.TypeToken;
import com.lws.basic.base.BaseFragment;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.TimeUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author 松
 * 2020/10/7 10:49
 * 列表
 */
public class ListFragment extends BaseFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.et_start)
    EditText mEtStart;
    @BindView(R.id.et_end)
    EditText mEtEnd;
    @BindView(R.id.sp_unit)
    Spinner mSpUnit;
    @BindView(R.id.sp_local)
    Spinner mSpLocal;
    @BindView(R.id.sp_type)
    Spinner mSpType;
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    Unbinder mUnbinder;
    private int mPage;
    private String mTypeId;   //类型id
    private String mPolicedepId;//局id
    private String mChild;//所id
    private List<PolicedeptBean.ChildBean> mChildBeanList;
    private ListFragmentAdapter mAdapter;


    @Override
    public int setLayoutId() {
        return R.layout.fragment_list;
    }

    @OnClick(R.id.btn_search)
    public void onViewClicked() {
    }

    @Override
    protected void initView(View rootView) {
        mUnbinder = ButterKnife.bind(this, rootView);
    }

    @Override
    protected void initData() {
        super.initData();
        initRv();
        initRefresh();
        initSpinner(((StatisticsActivity) getActivity()).getSpList());
        getData(search());
    }

    /**
     * 初始化下拉列表
     */
    private void initSpinner(List<QuerySuccessBean.DataBean.DataListBean.FieldValuesBean> list) {
        try {

            //类型下拉列表
            String problemtype = JsonUtils.queryGetFiled(list, "problemtype");
            Type type = new TypeToken<List<ProblemtypeBean>>() {
            }.getType();
            List<ProblemtypeBean> problemtypeBeanList = GsonUtils.getInstance().fromJson(problemtype, type);
            List<String> typeList = new ArrayList<>();
            typeList.add("全部");
            for (ProblemtypeBean bean : problemtypeBeanList) {
                typeList.add(bean.getName());
            }
            //默认类型id
            mTypeId = "0";
            //类型
            ArrayAdapter adapterType = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, typeList);
            mSpType.setAdapter(adapterType);
            mSpType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    MyLogger.i(position + "");
                    if (position == 0) {
                        mTypeId = "0";
                    } else {
                        mTypeId = problemtypeBeanList.get(position-1).getId() + "";
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            //局
            String policedept = JsonUtils.queryGetFiled(list, "policedept");
            Type policedeptType = new TypeToken<List<PolicedeptBean>>() {
            }.getType();
            List<PolicedeptBean> policedeptBeanList = GsonUtils.getInstance().fromJson(policedept, policedeptType);
            List<String> policedeptList = new ArrayList<>();
            policedeptList.add("全部");
            for (PolicedeptBean bean : policedeptBeanList) {
                policedeptList.add(bean.getName());
            }
            mPolicedepId = "0";
            //所
            mChildBeanList = new ArrayList<>();
            List<String> childList = new ArrayList<>();
            childList.add("全部");

            mChild = "0";
            ArrayAdapter adapterLocal = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, childList);
            mSpLocal.setAdapter(adapterLocal);
            mSpLocal.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position == 0) {
                        mChild = "0";
                    } else {
                        mChild = mChildBeanList.get(position - 1).getDeptid() + "";
                    }

                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            //局
            ArrayAdapter adapterUnit = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, policedeptList);
            mSpUnit.setAdapter(adapterUnit);
            mSpUnit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    List<String> childList = new ArrayList<>();
                    childList.add("全部");
                    mChild = "0";
                    adapterLocal.clear();
                    if (position == 0) {
                        mPolicedepId = "0";

//                        adapterLocal.clear();
//                        adapterLocal.addAll(childList);
                    } else {
                        mPolicedepId = policedeptBeanList.get(position - 1).getDeptid() + "";
                        mChildBeanList = policedeptBeanList.get(position - 1).getChild();
                        for (PolicedeptBean.ChildBean bean : policedeptBeanList.get(position - 1).getChild()) {
                            childList.add(bean.getName());
                        }

                    }
                    adapterLocal.addAll(childList);


                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
        } catch (Exception e) {
            MyToast.show(e.getMessage());
            MyLogger.i("统计分析下拉列表" + e.getMessage());
        }


    }

    /**
     * 获取数据
     */
    private void getData(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {
        ResourceApi inspectionRecordQuery = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.inspectionRecordQuery);

        mPage = 1;
        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();
//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);


        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(1);
        page.setPageSize(20);

        String json = JsonUtils.query(keyValueListBeanList, "dutycop,firstdept,seconddept,problemname,createdate,id"
                , inspectionRecordQuery.getResourceId(), orderByList, page, inspectionRecordQuery.getResourceRegionalismCode());
        LogUtils.logUpload("现场督察记录列表", "1", inspectionRecordQuery.getResourceId(), inspectionRecordQuery.getResourceAddress(), json, "", "成功", "","");

        OkHttpUtils.post(inspectionRecordQuery.getResourceAddress(), json, QuerySuccessBean.class).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();
                mSrl.finishRefresh();
                if (querySuccessBean.getCode().equals("200")) {
                    mAdapter.setNewData(querySuccessBean.getData().getDataList());
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }


    /**
     * 搜索条件
     */
    private List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> search() {
        String start = mEtStart.getText().toString();//
        String end = mEtEnd.getText().toString();//
        if (!TextUtils.isEmpty(end)){
            end+=" 23:59:59";
        }
        List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> list = new ArrayList<>();
        if (!mTypeId.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean1 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean1.setKey("inspecttype");
            bean1.setRelationOperator("=");
            bean1.setValue(mTypeId);
            list.add(bean1);
        }
        if (!mPolicedepId.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean2 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean2.setKey("firstleveldutyunit");
            bean2.setRelationOperator("=");
            bean2.setValue(mPolicedepId);
            list.add(bean2);
        }
        if (!mChild.equals("0")) {
            QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
            bean.setKey("secondleveldutyunit");
            bean.setRelationOperator("=");
            bean.setValue(mChild);
            list.add(bean);
        }
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean3 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean3.setKey("starttime");
        bean3.setRelationOperator(">=");
        bean3.setValue(start);
        list.add(bean3);
        QueryBean.ParameterBean.ConditionBean.KeyValueListBean bean4 = new QueryBean.ParameterBean.ConditionBean.KeyValueListBean();
        bean4.setKey("endtime");
        bean4.setRelationOperator("<=");
        bean4.setValue(end);
        list.add(bean4);
        return list;
    }

    /**
     * 加载更多
     */
    private void loadmore(List<QueryBean.ParameterBean.ConditionBean.KeyValueListBean> keyValueListBeanList) {

        ResourceApi inspectionRecordQuery = ResourceApiUtils.getResourceApi(MainActivity.resourceApiList, Constant.inspectionRecordQuery);

        mPage += 1;
        showLoading();
        List<QueryBean.ParameterBean.OrderByBean> orderByList = new ArrayList<>();

//        QueryBean.ParameterBean.OrderByBean order1 = new QueryBean.ParameterBean.OrderByBean();
//        order1.setSort("passdate");
//        order1.setSort("desc");
//        orderByList.add(order1);

        QueryBean.ParameterBean.PageBean page = new QueryBean.ParameterBean.PageBean();
        page.setPageNo(mPage);
        page.setPageSize(20);
        String json = JsonUtils.query(keyValueListBeanList, "dutycop,firstdept,seconddept,problemname,createdate,id"
                , inspectionRecordQuery.getResourceId(), orderByList, page, inspectionRecordQuery.getResourceRegionalismCode());
        OkHttpUtils.post(inspectionRecordQuery.getResourceAddress(), json, QuerySuccessBean.class).subscribe(new ObserverOnNext<QuerySuccessBean>() {
            @Override
            public void onNext(QuerySuccessBean querySuccessBean) {
                dismissLoading();
                mSrl.finishLoadmore();
                if (querySuccessBean.getCode().equals("200")) {
                    if (querySuccessBean.getData().getDataList().size() > 0) {
                        mAdapter.addData(querySuccessBean.getData().getDataList());
                    } else {
                        MyToast.show("没有更多数据了");
                    }
                } else {
                    MyToast.show(querySuccessBean.getMessage());
                }
            }
        });
    }



    /**
     * 初始化rv
     */
    private void initRv() {
        List<QuerySuccessBean.DataBean.DataListBean> list = new ArrayList<>();
        mRv.setLayoutManager(new LinearLayoutManager(getContext()));
         mAdapter = new ListFragmentAdapter(null);
        mRv.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    /**
     * 初始化上拉刷新 下拉加载更多
     */
    private void initRefresh() {
        //mSrl.setRefreshHeader(new DeliveryHeader(this));

        mSrl.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                  getData(search());
            }
        });
        mSrl.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                  loadmore(search());
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    /**
     * 显示时间
     */
    private void showTime(int flag) {
        TimePickerView pvTime = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                String time = TimeUtils.date2date(date);
                //1开始时间
                if (flag == 1) {
                    mEtStart.setText(time);
                }
                //结束时间
                if (flag == 2) {
                    mEtEnd.setText(time);
                }

                MyLogger.i(TimeUtils.date2date(date));

            }
        }).setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setBgColor(0xffd6ecf0)
                .setTitleBgColor(0xffd6ecf0)
                .setLabel("年", "月", "日", "", "", "")//默认设置为年月日时分秒
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(true)//是否显示为对话框样式
                .build();

        pvTime.show();
    }

    @OnClick({R.id.et_start, R.id.et_end, R.id.btn_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_start:
                showTime(1);
                break;
            case R.id.et_end:
                showTime(2);
                break;
            case R.id.btn_search:
                getData(search());
                break;
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        QuerySuccessBean.DataBean.DataListBean item = (QuerySuccessBean.DataBean.DataListBean) adapter.getData().get(position);
        Intent intent = new Intent(getContext(), InspectorRecordActivity.class);
        intent.putExtra("id",  JsonUtils.queryGetFiled(item.getFieldValues(), "id"));
        startActivity(intent);
    }
}
